<template>
  <el-drawer
    :close-on-press-escape="false"
    v-model="drawerVisible"
    size="1200px"
    :show-close="false"
    @close="handleClose"
  >
    <template #header>
      <div class="drawer-header">
        <div class="header-content">
          <span class="drawer-title">{{
            isEdit ? "修改用户" : "新增用户"
          }}</span>
        </div>
        <el-button type="text" @click="handleClose" class="close-btn"
          >关闭</el-button
        >
      </div>
    </template>

    <div class="form-container">
      <div class="form-layout">
        <div class="avatar-section">
          <img
            src="@/assets/images/icon/avatar_icon.png"
            alt="用户头像"
            class="avatar-image"
          />
        </div>
        <div class="form-section">
          <el-form
            :model="formData"
            :rules="formRules"
            ref="formRef"
            label-width="100px"
            class="user-form"
          >
            <el-form-item label="姓名" prop="real_name">
              <el-input
                v-model="formData.real_name"
                placeholder="请输入姓名"
                style="width: 400px"
              />
            </el-form-item>
            <el-form-item label="手机号" prop="phone">
              <el-input
                v-model="formData.phone"
                placeholder="请输入手机号"
                style="width: 400px"
              />
            </el-form-item>
            <el-form-item label="账户名" prop="user_name">
              <el-input
                v-model="formData.user_name"
                placeholder="请输入账户名"
                style="width: 400px"
              />
            </el-form-item>
            <el-form-item label="密码" prop="password">
              <el-input
                v-model="formData.password"
                placeholder="请输入密码"
                type="password"
                style="width: 400px"
              />
            </el-form-item>
            <el-form-item label="部门" prop="department_id">
              <el-select
                v-model="formData.department_id"
                placeholder="请选择部门"
                style="width: 400px"
              >
                <el-option
                  v-for="item in departmentsListData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="角色" prop="role_id">
              <el-select
                v-model="formData.role_id"
                placeholder="请选择角色"
                style="width: 400px"
              >
                <el-option
                  v-for="item in rolesListData"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item :label="isEdit ? '账号状态' : '状态'" prop="status">
              <el-radio-group v-model="formData.status">
                <el-radio :value="1">启用</el-radio>
                <el-radio :value="0">禁用</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>

    <template #footer>
      <el-button plain @click="handleClose" class="footer-btn">取消</el-button>
      <el-button type="primary" @click="handleSave" class="footer-btn"
        >保存</el-button
      >
    </template>
  </el-drawer>
</template>

<script setup>
import { ref, reactive, onMounted } from "vue";
import { userAdd, userUpdate, rolesList, departmentsList } from "@/api";
import { ElMessage } from "element-plus";
import md5 from "js-md5";

const drawerVisible = ref(false);
const formRef = ref(null);
const isEdit = ref(false);
const currentRow = ref(null);

const departmentsListData = ref([]);
const rolesListData = ref([]);

const formData = reactive({
  id: null,
  real_name: "",
  phone: "",
  user_name: "",
  password: "",
  department_id: "",
  role_id: "",
  status: 1,
});

const formRules = {
  real_name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  phone: [{ required: true, message: "请输入手机号", trigger: "blur" }],
  user_name: [{ required: true, message: "请输入账户名", trigger: "blur" }],
  password: [{ required: true, message: "请输入密码", trigger: "blur" }],
  department_id: [{ required: true, message: "请选择部门", trigger: "change" }],
  role_id: [{ required: true, message: "请选择角色", trigger: "change" }],
  status: [{ required: true, message: "请选择账户状态", trigger: "change" }],
};

const emit = defineEmits(["refresh"]);

defineOptions({
  name: "UserForm",
});

const getdepartmentsList = () => {
  departmentsList({ pageSize: 20, page: 1, is_not_limit: 1 }).then((res) => {
    if (res.code == 0) {
      departmentsListData.value = res.data || [];
    }
  });
};

const getrolesList = () => {
  rolesList({ pageSize: 20, page: 1, is_not_limit: 1 }).then((res) => {
    if (res.code == 0) {
      rolesListData.value = res.data || [];
    }
  });
};

onMounted(() => {
  getdepartmentsList();
  getrolesList();
});

// 新增用户
const openAddDrawer = () => {
  isEdit.value = false;
  resetForm();
  drawerVisible.value = true;
};

// 修改用户
const openEditDrawer = (row) => {
  isEdit.value = true;
  currentRow.value = row;
  // 填充表单数据
  formData.id = row.id;
  formData.real_name = row.real_name;
  formData.phone = row.phone;
  formData.user_name = row.user_name;
  formData.password = "";
  formData.department_id = row.department_id;
  formData.role_id = row.role_id;
  formData.status = row.status;
  drawerVisible.value = true;
};

// 重置表单
const resetForm = () => {
  formData.id = null;
  formData.real_name = "";
  formData.phone = "";
  formData.user_name = "";
  formData.password = "";
  formData.department_id = "";
  formData.role_id = "";
  formData.status = 1;
  if (formRef.value) {
    formRef.value.resetFields();
  }
};

const handleClose = () => {
  drawerVisible.value = false;
  resetForm();
};

const handleSave = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const submitData = { ...formData };
      submitData.password = md5(formData.password);

      if (isEdit.value) {
        // 修改用户
        userUpdate(submitData).then((res) => {
          if (res.code == 0) {
            ElMessage.success("修改成功");
            handleClose();
            emit("refresh");
          }
        });
      } else {
        // 新增用户
        userAdd(submitData).then((res) => {
          if (res.code == 0) {
            ElMessage.success("新增成功");
            handleClose();
            emit("refresh");
          }
        });
      }
    }
  });
};

defineExpose({
  openAddDrawer,
  openEditDrawer,
});
</script>

<style scoped lang="scss">
.drawer-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
  padding: 16px 20px;

  .header-content {
    display: flex;
    align-items: center;
    gap: 20px;
  }

  .drawer-title {
    font-size: 18px;
    font-weight: 600;
    color: #333;
  }

  .close-btn {
    font-size: 16px;
    padding: 13px 16px;
    border: 1px solid #595757;
    color: #000000;
    background: #fff;
    border-radius: 4px;

    &:hover {
      color: #409eff;
      border-color: #409eff;
    }
  }
}

.form-container {
  padding: 20px;
  .form-layout {
    display: flex;
    gap: 40px;
    align-items: flex-start;
  }
  .avatar-section {
    flex-shrink: 0;
    width: 200px;
    .avatar-image {
      width: 100%;
    }
  }
  .form-section {
    flex: 1;

    .user-form {
      max-width: 600px;
    }
  }
}

.footer-btn {
  padding: 13px 16px !important;
  border: 1px solid #595757 !important;
}

// 确保抽屉内容区域撑满全屏
:deep(.el-drawer__body) {
  padding: 0;
  height: calc(100vh - 60px);
  overflow: hidden;
}

:deep(.el-drawer) {
  width: 100% !important;
}

:deep(.el-drawer__wrapper) {
  width: 100% !important;
}
</style>
